﻿using CloudMusic.API;
using CloudMusic.Helper;
using CloudMusic.Model;
using DMSkin.Core.Common;
using DMSkin.Core.MVVM;
using Flurl;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CloudMusic.ViewModel
{
    public class MainWindowViewModel : MusicViewModelBase
    {
        #region 定义
        /// <summary>
        /// 当前页面/默认为发现音乐界面
        /// </summary>
        private Page currentPage = PageManager.PageFindMusic;
        public Page CurrentPage
        {
            get { return currentPage; }
            set
            {
                currentPage = value;
                OnPropertyChanged("CurrentPage");
            }
        }
        /// <summary>
        /// 桌面任务栏图标显示文字
        /// </summary>
        private string titleArtist = "网易云音乐";
        public string TitleArtist
        {
            get { return titleArtist; }
            set
            {
                titleArtist = value;
                OnPropertyChanged("TitleArtist");
            }
        }
        /// <summary>
        /// 播放模式-默认为列表循环
        /// </summary>
        private PlayModelState _playingMode = PlayModelState.Order;
        public PlayModelState PlayingMode
        {
            get
            {
                return _playingMode;
            }
            set
            {
                _playingMode = value;
                OnPropertyChanged("PlayingMode");
            }
        }
        /// <summary>
        /// 媒体播放进度
        /// </summary>
        private TimeSpan position;
        public TimeSpan Position
        {
            get { return position; }
            set
            {
                position = value;
                OnPropertyChanged("Position");
            }
        }
        /// <summary>
        /// 媒体总长度
        /// </summary>
        private TimeSpan duration = new TimeSpan(0);
        public TimeSpan Duration
        {
            get { return duration; }
            set
            {
                duration = value;
                OnPropertyChanged("Duration");
            }
        }
        /// <summary>
        /// 播放按钮提示信息
        /// </summary>
        public string _toolTip = "播放";
        public string ToolTip
        {
            get { return _toolTip; }
            set
            {
                _toolTip = value;
                OnPropertyChanged("ToolTip");
            }
        }
        /// <summary>
        /// 封面
        /// </summary>
        private BitmapImage _cover = CommonHelper.BitmapToBitmapImage(Properties.Resources.default_album);
        public BitmapImage Cover
        {
            get
            { return _cover; }
            set
            {
                _cover = value;
                OnPropertyChanged("Cover");
            }
        }
        /// <summary>
        /// 模糊图片封面
        /// </summary>
        private BitmapImage _blurPicUrl = CommonHelper.BitmapToBitmapImage(Properties.Resources.blurPicUrl);
        public BitmapImage blurPicUrl
        {
            get
            { return _blurPicUrl; }
            set
            {
                _blurPicUrl = value;
                OnPropertyChanged("blurPicUrl");
            }
        }
        /// <summary>
        /// 歌曲的喜欢状态
        /// </summary>
        private int like = 0;
        public int Like
        {
            get
            { return like; }
            set
            {
                like = value;
                OnPropertyChanged("Like");
            }
        }
        /// <summary>
        /// 播放器
        /// </summary>
        private MediaPlayer player = new MediaPlayer();
        public MediaPlayer Player
        {
            get
            {
                return player;
            }
            set
            {
                player = value;
                OnPropertyChanged("Player");
            }
        }
        /// <summary>
        /// 歌曲信息局栏小窗口
        /// </summary>
        private bool menuBottom = false;
        public bool MenuBottom
        {
            get
            {
                return menuBottom;
            }
            set
            {
                menuBottom = value;
                OnPropertyChanged("MenuBottom");
            }
        }
        /// <summary>
        /// 音乐详情界面唱片动画路由托管-播放按钮
        /// </summary>
        public static event EventHandler PlayBtnCommdEvent;
        /// <summary>
        /// 歌词滚动
        /// </summary>
        public static event EventHandler RollEvent;
        /// <summary>
        /// 获取歌词-自动
        /// </summary>
        public static event EventHandler LrcEvent;
        /// <summary>
        /// 音乐详情界面唱片动画路由托管-点击行
        /// </summary>
        public static event EventHandler UCEvent;
        /// <summary>
        /// 随机数
        /// </summary>
        private int[] j;

        #endregion

        public MainWindowViewModel()
        {
            //初始化播放器
            PlayManager.player = Player;
            PlayBtnLeft = "2 0 0 0";
            Task.Run(async () =>
            {
                while (true)
                {
                    //每隔900 毫秒更新 一次 播放数据
                    await Task.Delay(900);
                    if (PlayManager.State == PlayState.Play)
                    {
                        Execute.OnUIThread(() =>
                        {
                            //获取当前进度
                            Position = Player.Position;
                            //歌词位置
                            RollEvent?.Invoke(Player.Position.TotalMilliseconds, null);
                        });
                    }
                }
            });
            Player.MediaOpened += (sender, e) =>
            {
                try
                {
                    MenuBottom = true;
                    Duration = Player.NaturalDuration.TimeSpan;                
                    SelectedMusic = SelectMusicInfo;
                    SelectMusicInfo.Playing = true;
                    if (!HistoryMusicList.Any(t => t.Id == SelectedMusic.Id)) HistoryMusicList.Add(SelectedMusic);
                    ChangeCover(SelectedMusic);
                    TitleArtist = SelectedMusic.Name + "-" + SelectedMusic.Artist;
                    PlayBtnState = PlayState.Pause;
                    PlayBtnLeft = "0 0 0 0";
                    LrcEvent?.Invoke(SelectedMusic.Id, null);
                    UCEvent?.Invoke(null, null);
                }
                catch (Exception) { };

            };
            //player.MediaOpened
            Player.MediaEnded += (sender, e) =>
            {
                ChangeMusic(PlayingMode);
            };
        }

        #region 页面操作-选中的菜单
        private LeftMenuModel selectMenu;
        public LeftMenuModel SelectMenu
        {
            get { return selectMenu; }
            set
            {
                selectMenu = value;
                switch (selectMenu)
                {
                    case LeftMenuModel.Home:
                        CurrentPage = PageManager.PageEmpty;
                        break;
                    //跳转到本地音乐
                    case LeftMenuModel.LocalMusic:
                        CurrentPage = PageManager.PageLocalMusic;
                        break;
                    case LeftMenuModel.DownLoad:
                        CurrentPage = PageManager.PageDownLoad;
                        break;
                    case LeftMenuModel.CloudMusic:
                        CurrentPage = PageManager.PageCloudMusic;
                        break;
                    case LeftMenuModel.Collection:
                        CurrentPage = PageManager.PageCollection;
                        break;
                    case LeftMenuModel.FindMusic:
                        CurrentPage = PageManager.PageFindMusic;
                        break;
                    case LeftMenuModel.LookLive:
                        CurrentPage = PageManager.PageLookLive;
                        break;
                }
                OnPropertyChanged("SelectMenu");
            }
        }
        #endregion

        #region 上一曲
        public ICommand LastMusic
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    try
                    {
                        if (SelectMusicInfo == null) return;
                        var index = PlayListHelper.MainMusicList.IndexOf(PlayListHelper.MainMusicList.FirstOrDefault(t => t.Id == SelectMusicInfo.Id));
                        switch (PlayingMode)
                        {
                            //处于以下模式播放时，上一曲按照列表进行
                            case PlayModelState.Order:
                            case PlayModelState.RepeatAll:
                            case PlayModelState.RepeatOne:
                                if (index > 0)
                                {
                                    SelectMusicInfo.Playing = false;
                                    SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[index - 1];
                                    SelectMusicInfo.Playing = true;
                                }
                                else
                                {
                                    SelectMusicInfo.Playing = false;
                                    SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[PlayListHelper.MainMusicList.Count - 1];
                                    SelectMusicInfo.Playing = true;
                                }
                                break;
                            //处于随机时候，上一曲随机播放当前列表任意音乐，可重复以随机播放音乐
                            case PlayModelState.Random:
                                SelectMusicInfo.Playing = false;
                                j = CommonHelper.GetRandomArray(1, 0, PlayListHelper.MainMusicList.Count - 1);
                                SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[j[0]];
                                SelectMusicInfo.Playing = true;
                                break;

                        }
                        PlayManager.Play(SelectedMusic);
                    }
                    catch (Exception) { }
                });
            }
        }
        #endregion

        #region 下一曲
        public ICommand NextMusic
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    try
                    {
                        if (SelectMusicInfo == null) return;
                        var index = PlayListHelper.MainMusicList.IndexOf(PlayListHelper.MainMusicList.FirstOrDefault(t => t.Id == SelectMusicInfo.Id));
                        if (index > -1)
                        {
                            switch (PlayingMode)
                            {
                                case PlayModelState.Order:
                                case PlayModelState.RepeatAll:
                                case PlayModelState.RepeatOne:
                                    if (index < PlayListHelper.MainMusicList.Count - 1)
                                    {
                                        SelectMusicInfo.Playing = false;
                                        SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[index + 1];
                                        SelectMusicInfo.Playing = true;
                                    }
                                    else
                                    {
                                        SelectMusicInfo.Playing = false;
                                        SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[0];
                                        SelectMusicInfo.Playing = true;
                                    }
                                    break;
                                //处于随机时候，可重复以随机播放音乐
                                case PlayModelState.Random:
                                    SelectMusicInfo.Playing = false;
                                    j = CommonHelper.GetRandomArray(1, 0, PlayListHelper.MainMusicList.Count - 1);
                                    SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[j[0]];
                                    SelectMusicInfo.Playing = true;
                                    break;

                            }
                            PlayManager.Play(SelectedMusic);
                        }
                    }
                    catch (Exception) { }

                });
            }
        }
        #endregion

        #region 播放按钮状态
        public ICommand PlayBtnCommd
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    if (PlayListHelper.MainMusicList.Count == 0)
                    {
                        return;
                    }
                    else
                    {
                        string info = string.Empty;
                        PlayBtnCommdEvent.Invoke(PlayBtnState, null);
                        switch (PlayBtnState)
                        {
                            case PlayState.Play:
                                SelectMusicInfo.Playing = false;
                                if (SelectMusicInfo == null && PlayListHelper.MainMusicList.Count > 0)
                                {
                                    SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[0];
                                    PlayManager.Play(SelectedMusic);
                                   
                                }
                                else
                                {
                                    if (PlayingMode == PlayModelState.Order && Convert.ToInt32(SelectMusicInfo.Index) >= PlayListHelper.MainMusicList.Count)
                                    {
                                        SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[0];
                                        PlayManager.Play(SelectedMusic);
                                    }
                                    else
                                    {
                                        player.Play();
                                    }
                                }
                                PlayBtnLeft = "0 0 0 0";    
                                info = "暂停";
                                PlayBtnState = PlayState.Pause;
                                break;
                            case PlayState.Pause:
                                SelectMusicInfo.Playing = true;
                                player.Pause();
                                info = "播放";
                                PlayBtnLeft = "2 0 0 0";
                                PlayBtnState = PlayState.Play;
                                break;
                        }
                        ToolTip = info;
                    }

                });
            }
        }
        #endregion

        #region 音乐播放模式-单曲/循环。。。
        public void ChangeMusic(PlayModelState mode)
        {
            try
            {
                var index = PlayListHelper.MainMusicList.IndexOf(PlayListHelper.MainMusicList.FirstOrDefault(t => t.Id == SelectMusicInfo.Id));
                if (index == -1) return;
                switch (mode)
                {
                    case PlayModelState.Order:
                        if (index < PlayListHelper.MainMusicList.Count)
                        {
                            if (index == PlayListHelper.MainMusicList.Count - 1)
                            {
                                player.Pause();
                                PlayBtnState = PlayState.Play;
                                return;
                            }
                            else
                            {
                                SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[index + 1];
                            }
                        }
                        break;
                    case PlayModelState.RepeatAll:
                        if (index >= PlayListHelper.MainMusicList.Count - 1)
                        {
                            SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[0];
                        }
                        else
                        {
                            SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[index + 1];
                        }
                        break;
                    case PlayModelState.RepeatOne:
                        player.Position = new TimeSpan(0);
                        break;
                    case PlayModelState.Random:
                        j = CommonHelper.GetRandomArray(1, 0, PlayListHelper.MainMusicList.Count - 1);
                        SelectedMusic = SelectMusicInfo = PlayListHelper.MainMusicList[j[0]];
                        break;
                }
                SelectMusicInfo.Playing = false;
                PlayManager.Play(SelectedMusic);
            }
            catch (Exception) { }
        }
        #endregion

        #region 切换播放模式
        public ICommand ChangePlayingMode
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    PlayingMode++;
                    if ((int)PlayingMode > 3) PlayingMode = PlayModelState.Order;
                    string info = string.Empty;
                    switch (PlayingMode)
                    {
                        case PlayModelState.Order:
                            info = "顺序播放";
                            break;
                        case PlayModelState.RepeatOne:
                            info = "单曲循环";
                            break;
                        case PlayModelState.RepeatAll:
                            info = "全部循环";
                            break;
                        case PlayModelState.Random:
                            info = "随机播放";
                            break;
                    }

                });
            }
        }
        #endregion

        #region 处理音乐封面
        public void ChangeCover(PlayModel t)
        {
            if (t.Type == 0)
            {
                var tfile = TagLib.File.Create(t.Url);

                BitmapImage bitmap = null;
                var pics = tfile.Tag.Pictures;
                if (pics != null && pics.Length > 0)
                {
                    TagLib.IPicture pic = pics[0];
                    using (var stream = new MemoryStream(pic.Data.Data))
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.CacheOption = BitmapCacheOption.OnLoad;
                        bitmap.StreamSource = stream;
                        bitmap.EndInit();
                        bitmap.Freeze();
                    }
                    blurPicUrl = Cover = bitmap;
                }
                else
                {
                    blurPicUrl = Cover = CommonHelper.BitmapToBitmapImage(Properties.Resources.default_album);
                }
            }
            else
            {
                blurPicUrl = Cover = new BitmapImage(new Uri(t.PicUrl));
              
            }
        }

        #endregion

        #region 清空列表
        /// <summary>
        /// 播放歌单清空
        /// </summary>
        public ICommand EmptyPlayList
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    if (PlayListHelper.MainMusicList.Count>0)
                    {
                        PlayListHelper.MainMusicList.Clear();
                        PlayInfo.Clear();
                        PlayBtnState = PlayState.Play;
                        player.Stop();
                        MenuBottom = false;
                        PlayBtnLeft = "2 0 0 0";
                    }
                });
            }
        }
        /// <summary>
        ///清空历史播放列表
        /// </summary>
        public ICommand HistoryClear
        {
            get
            {
                return new DelegateCommand(obj =>
                {
                    if (HistoryMusicList.Count > 0)
                    {
                        HistoryMusicList.Clear();
                    }
                });
            }
        }
        #endregion
    }
}
